package com.example.equipmentjava.xiaoxinyan.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.equipmentjava.xiaoxinyan.TimedYController;
import com.example.equipmentjava.xiaoxinyan.pojo.PushCallLog;
import com.example.equipmentjava.xiaoxinyan.pojo.PushCallThePolice;
import com.example.equipmentjava.xiaoxinyan.pojo.PushStatusNotification;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 邓昕劼
 * @version 1.3
 */
public class Utils {

    public static final Logger logger = LoggerFactory.getLogger(Utils.class);

    /**
     * 长护健康启效云对接接口的AppKey以及appSecret
     **/
    private static final String appKey = "d3aa45bbd1e94d70b5fe59b1fa37da21";
    private static final String appSecret = "883fbc209be344e899544af7c7caa0fc";
    private static final String qxUrl = "https://changhu.qixiaocloud.com";

    //正则表达式 解析睡眠检测带
    private static final Pattern regex = Pattern.compile("(?:HR|BM)\\[(\\d+),\\W*(\\d+)\\]");
    public static void main(String[] args) {
        String eventInfo = "HR[60,20]"; // 取值 eventInfo 字段
        Matcher regexMatcher = regex.matcher(eventInfo);
        if (regexMatcher.find() && eventInfo.startsWith("HR")) {
            System.out.println("心跳：" + regexMatcher.group(1) + "；呼吸：" + regexMatcher.group(2));
        }else{
            System.out.println("1");
        }
    }

    /**
     * 删除用户User
     */
    public static String DeleteUser(String name, String sn,String UUID, String userid){
        try {
            //新增用户到合作方系统
            String url = "https://unit.iotguard.cn/u/account/"+UUID+"/delete.do?userId="+userid;
            Map<String, Object> params = new HashMap<>();
            String response = SSLBypassUtil.sendPost(url, params);
            return response;
        } catch (Exception je) {
            je.printStackTrace();
            return null;
        }

    }

    /**
     * 修改用户User
     */
    public static String UpdateUser(String name,String gender,String birthday,String telephone,String sn,String address,String UUID,String userid){
        try {
            //新增用户到合作方系统
            String url = "https://unit.iotguard.cn/u/account/"+UUID+"/modify.do?userId="+userid;
            Map<String, Object> params = new HashMap<>();
            params.put("name", name);
            params.put("gender", gender);
            params.put("birthday", birthday);
            params.put("telephone", telephone);
            params.put("sn", sn);
            params.put("address", address);
            String response = SSLBypassUtil.sendPost(url, params);
            return response;
        } catch (Exception je) {
            je.printStackTrace();
            return null;
        }

    }



    /**
     * 新增用户User
     */
    public static String InsertUser(String name,String gender,String birthday,String telephone,String sn,String address,String UUID){
        try {
            //新增用户到合作方系统
            String url = "https://unit.iotguard.cn/u/account/"+UUID+"/create.do";
            Map<String, Object> params = new HashMap<>();
            params.put("name", name);
            params.put("gender", gender);
            params.put("birthday", birthday);
            params.put("telephone", telephone);
            params.put("sn", sn);
            params.put("address", address);
           return SSLBypassUtil.sendPost(url, params);
        } catch (Exception je) {
            je.printStackTrace();
            return null;
        }

    }





    /**
     * 报警事件通知接口
     * @param Json
     * @return
     */
    public static PushCallThePolice PushCallThePolice(net.sf.json.JSONObject Json) {
        try {
            PushCallThePolice pushCallThePolice = new PushCallThePolice();
            pushCallThePolice.setUnitCode(Json.getString("unitCode"));
            pushCallThePolice.setUnitName(Json.getString("unitName"));
            pushCallThePolice.setUserCode(Json.getString("userCode"));
            pushCallThePolice.setUserName(Json.getString("userName"));
            pushCallThePolice.setUserType(Json.getString("userType"));
            pushCallThePolice.setUserAddress(Json.getString("userAddress"));
            pushCallThePolice.setUserMobile(Json.getString("userMobile"));
            pushCallThePolice.setDeviceName(Json.getString("deviceName"));
            pushCallThePolice.setIsAlarm(Json.getString("isAlarm"));
            if (Json.getString("isAlarm").equals("false")) {
                pushCallThePolice.setIsAlarm("否");
            }
            if (Json.getString("isAlarm").equals("true")) {
                pushCallThePolice.setIsAlarm("是");
            }
            if (Json.getString("isAlarm").equals("1")) {
                pushCallThePolice.setIsAlarm("是");
            }
            if (Json.getString("isAlarm").equals("00")) {
                pushCallThePolice.setIsAlarm("否");
            }
            pushCallThePolice.setExtraType(Json.getString("extraType"));
            pushCallThePolice.setExtraCode(extraCode(Json.getString("extraCode")));
            pushCallThePolice.setExtraAddress(Json.getString("extraAddress"));
            pushCallThePolice.setEventName(Json.getString("eventName"));
            pushCallThePolice.setEventDesc(Json.getString("eventDesc"));
            pushCallThePolice.setEventTime(Json.getString("eventTime"));
            //解析睡眠检测带数据
            Matcher regexMatcher = regex.matcher(Json.getString("eventInfo"));
            if (regexMatcher.find() && Json.getString("eventInfo").startsWith("HR")) {
                pushCallThePolice.setEventInfo("心跳：" + regexMatcher.group(1) + "；呼吸：" + regexMatcher.group(2));
            }else{
                pushCallThePolice.setEventInfo(Json.getString("eventInfo"));
            }
            String qxToken = token();
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            String url = "https://apaas.qixiaocloud.com/open/qx-apaas-lowcode/XXY/PushCallThePolice";
            headMap.put("Authorization", qxToken);
            param = new HashMap();
            param.put("unitCode", pushCallThePolice.getUnitCode());
            param.put("unitName", pushCallThePolice.getUnitName());
            param.put("userCode", pushCallThePolice.getUserCode());
            param.put("userName", pushCallThePolice.getUserName());
            param.put("userType", pushCallThePolice.getUserType());
            param.put("userAddress", pushCallThePolice.getUserAddress());
            param.put("userMobile", pushCallThePolice.getUserMobile());
            param.put("deviceName", pushCallThePolice.getDeviceName());
            param.put("isAlarm", pushCallThePolice.getIsAlarm());
            param.put("extraType", pushCallThePolice.getExtraType());
            param.put("extraCode", pushCallThePolice.getExtraCode());
            param.put("extraAddress", pushCallThePolice.getExtraAddress());
            param.put("eventName", pushCallThePolice.getEventName());
            param.put("eventDesc", pushCallThePolice.getEventDesc());
            param.put("eventTime", pushCallThePolice.getEventTime());
            param.put("eventInfo", pushCallThePolice.getEventInfo());
            String qxAdd = postJsonParam(url, param, headMap);
            logger.info("孝心眼--报警事件通知接口--提交启效结果：" + qxAdd);
            return pushCallThePolice;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("报错 = " + e);
        }
        return null;
    }




    /**
     * 通话日志
     * @param Json
     * @return
     */
    public static PushCallLog PushCallLog(net.sf.json.JSONObject Json) {
        try {
            PushCallLog pushCallLog = new PushCallLog();
            pushCallLog.setCaller(Json.getString("caller"));
            pushCallLog.setCallerDevice(Json.getString("callerDevice"));
            pushCallLog.setCallerName(Json.getString("callerName"));
            pushCallLog.setCallee(Json.getString("callee"));
            pushCallLog.setCalleeDevice(Json.getString("calleeDevice"));
            pushCallLog.setCalleeName(Json.getString("calleeName"));
            if (Json.getString("callType").equals("1")){
                pushCallLog.setCallType("来电");
            }
            if (Json.getString("callType").equals("2")){
                pushCallLog.setCallType("去电");
            }
            if (Json.getString("callLine").equals("0")){
                pushCallLog.setCallLine("4G通话");
            }
            if (Json.getString("callLine").equals("1")){
                pushCallLog.setCallLine("WIFI通话");
            }
            pushCallLog.setRingUp(Json.getString("ringUp"));
            pushCallLog.setRingtone(Json.getString("ringtone")+"s");
            pushCallLog.setAnswered(Json.getString("answered"));
            if (Json.getString("duration").equals("-1")){
                pushCallLog.setCallLine("未接听");
            }else{
                pushCallLog.setDuration(Json.getString("duration")+"s");
            }
            pushCallLog.setHangUp(Json.getString("hangUp"));
            String qxToken = token();
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            String url = "https://apaas.qixiaocloud.com/open/qx-apaas-lowcode/XXY/PushCallLog";
            headMap.put("Authorization", qxToken);
            param = new HashMap();
            param.put("caller", pushCallLog.getCaller());
            param.put("callerDevice", pushCallLog.getCallerDevice());
            param.put("callerName", pushCallLog.getCallerName());
            param.put("callee", pushCallLog.getCallee());
            param.put("calleeDevice", pushCallLog.getCalleeDevice());
            param.put("calleeName", pushCallLog.getCalleeName());
            param.put("callType", pushCallLog.getCallType());
            param.put("callLine", pushCallLog.getCallLine());
            param.put("ringUp", pushCallLog.getRingUp());
            param.put("ringtone", pushCallLog.getRingtone());
            param.put("answered", pushCallLog.getAnswered());
            param.put("duration", pushCallLog.getDuration());
            param.put("hangUp", pushCallLog.getHangUp());
            String qxAdd = postJsonParam(url, param, headMap);
            logger.info("孝心眼--通话日志--提交启效结果：" + qxAdd);
            return pushCallLog;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("报错 = " + e);
        }
        return null;
    }


    /**
     * 状态通知
     * @param Json
     * @return
     */
    public static PushStatusNotification PushStatusNotification(net.sf.json.JSONObject Json) {
        try {
            PushStatusNotification pushStatusNotification = new PushStatusNotification();
            pushStatusNotification.setDeviceId(Json.getString("deviceId"));
            pushStatusNotification.setSignal(Json.getString("signal") + "%");
            if (Json.getString("mode").equals("1")) {
                pushStatusNotification.setMode("外出");
            } else {
                pushStatusNotification.setMode("在家");
            }
            if (Json.getString("state").equals("0")) {
                pushStatusNotification.setState("撤防");
            }
            if (Json.getString("state").equals("1")) {
                pushStatusNotification.setState("布防");
            }
            if (Json.getString("state").equals("2")) {
                pushStatusNotification.setState("正在报警");
            }
            if (Json.getString("state").equals("3")) {
                pushStatusNotification.setState("在家布防");
            }
            pushStatusNotification.setPower(Json.getString("power") + "%");
            if (Json.getString("charging").equals("false")) {
                pushStatusNotification.setCharging("否");
            }
            if (Json.getString("charging").equals("true")) {
                pushStatusNotification.setCharging("是");
            }
            pushStatusNotification.setTemperature(Json.getString("temperature") + "摄氏度");
            pushStatusNotification.setVolume(Json.getString("volume"));
            pushStatusNotification.setVersion(Json.getString("version"));
            pushStatusNotification.setAccessories(Json.getString("accessories") + "个");
            pushStatusNotification.setMessages(Json.getString("messages") + "条");
            if (Json.getString("network").equals("0")) {
                pushStatusNotification.setNetwork("4G");
            }
            if (Json.getString("network").equals("1")) {
                pushStatusNotification.setNetwork("WIFI");
            }
            if (Json.getString("recording").equals("0")) {
                pushStatusNotification.setRecording("关闭状态");
            }
            if (Json.getString("recording").equals("1")) {
                pushStatusNotification.setRecording("正在录制本地视频");
            }
            if (Json.getString("status").equals("1")) {
                pushStatusNotification.setStatus("心跳异常");
            }
            if (Json.getString("status").equals("2")) {
                pushStatusNotification.setStatus("低电量");
            }
            if (Json.getString("status").equals("4")) {
                pushStatusNotification.setStatus("未闭合");
            }
            if (Json.getString("online").equals("false")) {
                pushStatusNotification.setOnline("离线");
            }
            if (Json.getString("online").equals("true")) {
                pushStatusNotification.setOnline("在线");
            }
            String qxToken = token();
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            String url = "https://apaas.qixiaocloud.com/open/qx-apaas-lowcode/XXY/PushStatusNotification";
            headMap.put("Authorization", qxToken);
            param = new HashMap();
            param.put("deviceId", pushStatusNotification.getDeviceId());
            param.put("signal", pushStatusNotification.getSignal());
            param.put("mode", pushStatusNotification.getMode());
            param.put("state", pushStatusNotification.getState());
            param.put("power", pushStatusNotification.getPower());
            param.put("charging", pushStatusNotification.getCharging());
            param.put("temperature", pushStatusNotification.getTemperature());
            param.put("volume", pushStatusNotification.getVolume());
            param.put("version", pushStatusNotification.getVersion());
            param.put("accessories", pushStatusNotification.getAccessories());
            param.put("messages", pushStatusNotification.getMessages());
            param.put("network", pushStatusNotification.getNetwork());
            param.put("recording", pushStatusNotification.getRecording());
            param.put("status", pushStatusNotification.getStatus());
            param.put("online", pushStatusNotification.getOnline());
            String qxAdd = postJsonParam(url, param, headMap);
            logger.info("孝心眼--设备状态的实时通知接口--提交启效结果：" + qxAdd);
            return pushStatusNotification;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("报错 = " + e);
        }
        return null;
    }

    public static String extraCode(String extraCode){
        switch (extraCode) {
            case "0":
                return "主机按键 SOS";
            case "1":
                return "主机语音 SOS";
            case "2":
                return "主机SOS取消键(S20)";
            case "3":
                return "主机拉绳SOS";
            case "4":
                return "主机发起服务请求";
            case "5":
                return "睡眠检测带(S18)";
            case "110":
                return "门铃低电量";
            case "1120":
                return "门铃恢复电量";
            case "112":
                return "门铃按下";
            case "120":
                return "呼叫铃低电量";
            case "1220":
                return "呼叫铃恢复电量";
            case "122":
                return "呼叫铃按下";
            case "130":
                return "外出模式开关低电量";
            case "1320":
                return "外出模式开关恢复电量";
            case "132":
                return "外出模式开关按下";
            case "140":
                return "服务铃低电量";
            case "1420":
                return "服务铃恢复电量";
            case "142":
                return "服务铃按下";
            case "150":
                return "门磁低电量";
            case "1520":
                return "门磁恢复电量";
            case "152":
                return "门磁未闭合";
            case "153":
                return "门磁未闭合";
            case "156":
                return "门磁闭合";
            case "157":
                return "门磁闭合";
            case "1521":
                return "门磁配件心跳异常";
            case "1514":
                return "门磁打开";
            case "166":
                return "气感正常心跳";
            case "1621":
                return "气感配件心跳异常";
            case "1614":
                return "气感触发";
            case "170":
                return "SOS 低电量";
            case "1720":
                return "SOS 恢复电量";
            case "176":
                return "SOS 正常心跳";
            case "1721":
                return "SOS 配件心跳异常";
            case "178":
                return "SOS 触发";
            case "180":
                return "烟感低电量";
            case "1820":
                return "烟感恢复电量";
            case "186":
                return "烟感正常心跳";
            case "1821":
                return "烟感配件心跳异常";
            case "188":
                return "烟感触发";
            case "1910":
                return "红外触发";
            case "1915":
                return "红外低电量";
            case "1920":
                return "红外恢复电量";
            case "200":
                return "标准版遥控器低电量";
            case "2020":
                return "标准版遥控器恢复电量";
            case "2012":
                return "标准版遥控器触发";
            case "210":
                return "孝心眼遥控器低电量";
            case "2120":
                return "孝心眼遥控器恢复电量";
            case "2112":
                return "孝心眼遥控器触发";
            case "220":
                return "水浸报警器低电量";
            case "2220":
                return "水浸报警器恢复电量";
            case "226":
                return "水浸报警器正常心跳";
            case "2221":
                return "水浸报警器配件心跳异常";
            case "2212":
                return "水浸报警器触发";
            case "231":
                return "睡眠监测带心率异常";
            case "233":
                return "睡眠监测带呼吸异常";
            case "234":
                return "睡眠监测带入床";
            case "235":
                return "睡眠监测带配对";
            case "236":
                return "睡眠监测带正常心跳";
            case "2321":
                return "睡眠监测带配件心跳异常";
            case "2316":
                return "睡眠监测带在床异常";
            case "2317":
                return "睡眠监测带心率";
            case "2318":
                return "睡眠监测带体动";
            case "2310":
                return "睡眠监测带离床";
            case "2313":
                return "睡眠监测带打鼾";
            case "2314":
                return "睡眠监测带翻身";
            case "238":
                return "睡眠监测带 SOS 按键";
            case "2312":
                return "睡眠监测带 SOS 取消";
            case "248":
                return "一氧化碳报警器触发";
            case "256":
                return "气感正常心跳";
            case "252":
            case "253":
                return "气感异常";
            case "2522":
                return "气感浓度值";
            case "2511":
                return "气感触发报警";
            case "2521":
                return "配件状态异常";
            case "26":
                return "低电量";
            case "268":
                return "SOS报警";
            case "2610":
                return "红外触发";
            case "27":
                return "低电量";
            case "278":
                return "SOS报警";
            case "2710":
                return "红外触发";
            case "2714":
                return "门磁打开";
            case "276":
                return "门磁关闭";
            case "273":
                return "门磁未关闭";
            case "2715":
                return "门铃触发";
            case "271":
                return "出门";
            case "272":
                return "进门";
            default:
                return "未知代码";
        }
    }







    /**
     * 生成token
     */
    public static String token() {
        try {
            String url = qxUrl + "/open/oauth/token";
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            param.put("appKey", appKey);
            param.put("appSecret", appSecret);
            String qxLogin = null;
            qxLogin = postJsonParam(url, param, headMap);
            net.sf.json.JSONObject qxLoginJson = net.sf.json.JSONObject.fromObject(qxLogin);
//            logger.info("token获取：" + qxLogin);
            String success = qxLoginJson.getString("success");
            if ("true".equals(success)) {
                net.sf.json.JSONObject qxData = net.sf.json.JSONObject.fromObject(qxLoginJson.getString("data"));
                String qxToken = qxData.getString("access_token");
                //将token存到redis设置全局有效时间 10分钟
//                System.out.println("token = " + stringRedisTemplate);
                return qxToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将map数据转成json数据
     */
    public static String postJsonParam(String url, Map<String, String> param, Map<String, String> headMap) throws Exception {
        String jsonparam = mapToJSON(param);
//        logger.info("请求参数串：" +jsonparam);
//        System.out.println("jsonparam = " + jsonparam);
        return doPost(url, jsonparam, headMap);
    }

    /**
     * map 转 json
     *
     * @param param
     * @return
     */
    public static String mapToJSON(Map param) {
        String json = JSON.toJSONString(param);
        return json;
    }

    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @param headMap
     * @return
     */
    public static String doPost(String url, String params, Map<String, String> headMap) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        //如果headMap不为空，则需要添加接口鉴权字段
        if (headMap != null) {
            Iterator it = headMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                httpPost.setHeader(key, headMap.get(key));
            }
        }
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
                return jsonString;
            } else {
                System.out.println("!!!!!!!!responseEntity:" + EntityUtils.toString(response.getEntity(), "UTF-8"));
                return "请求失败，服务器状态码：" + state;
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
